<template>
  <div>
    <a-form :form="form">
      <a-form-item
        :label="formItem.label"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        v-for="formItem in formOptions"
        :key="formItem.label">
        <component
          :is="'a-' + formItem.type"
          v-bind="formItem.attrs"
          v-on="formItem.listeners"
          v-decorator="formItem.dec">
          <slot v-if="formItem.type === 'select'">
            <a-select-option
              v-for="option in formItem.attrs.options"
              :key="option.label"
              :value="option.value">{{ option.label }}</a-select-option>
          </slot>
          <slot v-if="formItem.type === 'upload'">
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传</div>
            </div>
          </slot>
        </component>
      </a-form-item>
      <a-form-item :wrapperCol="{span: 19, offset: 7}">
        <a-button type="primary" @click="save">保存</a-button>
        <a-button type="primary" :loading="confirmLoading" @click="submit" style="margin-left: 30px">提交</a-button>
      </a-form-item>
    </a-form>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import av from '../../api/av'
import Vue from 'vue'
import moment from 'moment'
export default {
  name: 'SignUpForm',
  data () {
    return {
      confirmLoading: false,
      previewVisible: false,
      previewImage: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      },
      fileList: [],
      formOptions: [
        { label: '姓名',
          type: 'input',
          dec: ['name', { rules: [
            { required: true, message: '请输入姓名' }
          ] }] },
        { label: '身份证号',
          type: 'input',
          dec: ['idNum', { rules: [
            { required: true, message: '请输入身份证号' },
            { pattern: /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/,
              message: '请输入正确的身份证号',
              trigger: 'change' }
          ] } ] },
        { label: '性别',
          type: 'select',
          attrs: { options: [
            { value: '男', label: '男' },
            { value: '女', label: '女' }
          ] },
          dec: ['gender', { rules: [
            { required: true, message: '请输入介绍' }
          ] }]
        },
        { label: '出生年月',
          type: 'date-picker',
          dec: ['birth', { rules: [{ type: 'object', required: true, message: '请选择出生年月' }] }],
          attrs: { placeholder: '请选择出生年月' }
        },
        { label: '籍贯',
          type: 'input',
          dec: ['birthplace', { rules: [
            { required: true, message: '请输入籍贯' }
          ] }] },
        { label: '民族',
          type: 'input',
          dec: ['minzu', { rules: [
            { required: true, message: '请输入民族' }
          ] }] },
        { label: '学历层次',
          type: 'input',
          attrs: { options: [
            { value: '博士后', label: '博士后' },
            { value: '博士', label: '博士' },
            { value: '本科', label: '本科' },
            { value: '专科', label: '专科' },
            { value: '高中', label: '高中' }
          ] },
          dec: ['education', { rules: [
            { required: true, message: '请选择学历层次' }
          ] }] },
        { label: '照片上传',
          type: 'upload',
          attrs: {
            name: 'file',
            action: 'https://upload-z1.qiniup.com',
            'list-type': 'picture',
            data: {
              'token': 'XDoSJiRUevVGA5GxjtOxik35hPvwHJyqvYso-8rv:jK6S7M2d55mFMbtJaSM-UqnlKs4=:eyJzY29wZSI6InB0aGJtIiwicmV0dXJuVXJsIjoiIiwicmV0dXJuQm9keSI6IiIsImRlYWRsaW5lIjoxNTcxMjkzNDg2fQ=='
            },
            accept: 'image/*'
          },
          listeners: {
            preview: (file) => {
              this.previewImage = file.url || file.thumbUrl
              this.previewVisible = true
            },
            change: ({ file, fileList }) => {
              this.fileList = fileList
              const status = file.status
              if (status === 'done') {
                this.$message.success('上传成功')
              } else if (status === 'error') {
                this.$message.error(`上传失败`)
              }
            }
          },
          dec: ['imgUrl', { valuePropName: 'fileList',
            getValueFromEvent: this.normFile,
            rules: [
              { required: true, message: '请上传图片' }]
          }] },
        { label: '毕业时间',
          type: 'date-picker',
          dec: ['graduation', { rules: [{ type: 'object', required: true, message: '请选择毕业时间' }] }],
          attrs: { placeholder: '请选择毕业时间' }
        },
        { label: '院校',
          type: 'input',
          dec: ['school', { rules: [
            { required: true, message: '请输入院校' }
          ] }] },
        { label: '专业',
          type: 'input',
          dec: ['profession', { rules: [
            { required: true, message: '请输入专业' }
          ] }] },
        { label: '报考单位',
          type: 'input',
          dec: ['baokaodanwei', { rules: [
            { required: true, message: '请输入报考单位' }
          ] }] },
        { label: '岗位代码',
          type: 'input',
          dec: ['jobCode', { rules: [
            { required: true, message: '请输入岗位代码' }
          ] }] },
        { label: '毕业证书编号',
          type: 'input',
          dec: ['diplomaNumber', { rules: [
            { required: true, message: '请输入毕业证书编号' }
          ] }] },
        { label: '个人简介',
          type: 'textarea',
          dec: ['personalProfile', { rules: [
            { required: true, message: '请输入个人简介' }
          ] }] }
      ],
      form: this.$form.createForm(this),
      id: ''
    }
  },
  methods: {
    handleCancel () {
      this.previewVisible = false
    },
    normFile  (e) {
      console.log('Upload event:', e)
      // if (e.file.status === 'done') {
      //   return 'http://pzcpi7v4h.bkt.clouddn.com/' + e.file.response.hash
      // }
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList
    },
    handleChange ({ fileList }) {
      this.fileList = fileList
    },
    submit () {
      const { form: { validateFields } } = this
      // 先校验，通过表单校验后，才进入下一步
      validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          values.graduation = values.graduation.format('YYYY-MM-DD')
          values.birth = values.birth.format('YYYY-MM-DD')
          values.imgUrl = 'http://pzcpi7v4h.bkt.clouddn.com/' + values.imgUrl[0].response.hash
          av.add('signUp', values).then(res => {
            this.$message.success('新增成功')
            this.id = res.id
            this.$emit('nextStep', res._serverData)
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    save () {
      const { form: { getFieldsValue, validateFields } } = this
      const graduation = this.form.getFieldsValue(['graduation'])
      const birth = this.form.getFieldsValue(['birth'])
      const savedData = this.form.getFieldsValue()
      savedData.graduation = graduation.graduation.format('YYYY-MM-DD')
      savedData.birth = birth.birth.format('YYYY-MM-DD')
      // savedData.upload = []
      delete savedData.upload
      // savedData.upload = 'http://pzcpi7v4h.bkt.clouddn.com/' + savedData.upload
      Vue.ls.set('signUpData', savedData)
    }
  },
  mounted () {
    const data = Vue.ls.get('signUpData')
    data.graduation = moment(data.graduation)
    data.birth = moment(data.birth)
    const { form: { setFieldsValue } } = this
    this.$nextTick(() => {
      setFieldsValue(data)
    })
  }
}
</script>

<style lang="less" scoped>
  /deep/ .ant-form-item{
    margin-bottom: 2px;
  }
  /deep/ .ant-upload{
    &.ant-upload-select-picture {
      border: 1px dashed #d9d9d9;
      width: 104px;
      height: 104px;
      border-radius: 4px;
      background-color: #fafafa;
      text-align: center;
      cursor: pointer;
      transition: border-color 0.3s ease;
      vertical-align: top;
      margin-right: 8px;
      margin-bottom: 8px;
      display: table;
      &> .ant-upload-btn{
        width: 100%;
        height: 100%;
        display: table-cell;
        text-align: center;
        vertical-align: middle;
        padding: 8px;
      }
    }
  }
  /deep/ .ant-upload-list-picture{
    .ant-upload-list-item{
      /*float: left;*/
      /*width: 104px;*/
      /*height: 104px;*/
      /*margin: 0 8px 8px 0;*/
    }
    .ant-upload-list-item{
      /*height: 100%;*/
      /*position: relative;*/
      /*overflow: hidden;*/
    }
  }
</style>
